<template>
  <el-form ref="formRef" :model="form" :rules="rules" label-width="0" size="large" @keyup.enter="submitLogin">
    <el-form-item prop="mobile">
      <el-input v-model="form.mobile" prefix-icon="el-icon-iphone" clearable placeholder="请输入手机号码"></el-input>
    </el-form-item>
    <el-form-item prop="password">
      <el-input
        v-model="form.password"
        prefix-icon="el-icon-lock"
        clearable
        show-password
        placeholder="请输入密码"
      ></el-input>
    </el-form-item>
    <el-form-item style="margin-bottom: 10px">
      <el-col :span="12">
        <el-checkbox label="30天免登录" v-model="form.auto"></el-checkbox>
      </el-col>
      <el-col :span="12" class="login-forgot">
        <router-link to="/resetPassword">忘记密码？</router-link>
      </el-col>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" style="width: 100%" :loading="loginLoading" round @click="submitLogin">登录</el-button>
    </el-form-item>
  </el-form>
</template>

<script setup lang="ts">
import to from '@/utils/to'
import defaultConfig from '@/config'
import { ref, reactive } from 'vue'
import { AuthApi } from '@/api/auth'
import { IAuth } from '@/api/auth/type'
import { useUserStore } from '@/stores/modules/user'
import { useRoute, useRouter } from 'vue-router'
import { FormRules, FormInstance, ElNotification } from 'element-plus'
import { initDynamicRouter } from '@/routers/modules/dynamicRouter'
const $route = useRoute()
const $router = useRouter()
const userStore = useUserStore()

// 收集表单数据
const formRef = ref<FormInstance>()
const loginLoading = ref<boolean>(false)
const form: IAuth.LoginForm = reactive({ mobile: '17705324019', password: '12345678', auto: false })
const rules = reactive<FormRules<IAuth.LoginForm>>({
  mobile: [
    { required: true, len: 11, message: '请输入手机号码', trigger: 'blur' },
    { pattern: /^1[3456789]\d{9}$/, message: '手机号码格式不正确', trigger: 'blur' }
  ],
  password: [{ required: true, min: 8, max: 20, message: '密码长度为8-20位', trigger: 'blur' }]
})
// 登录
const submitLogin = async () => {
  try {
    if (await to(formRef.value!.validate())) return
    loginLoading.value = true
    let model: IAuth.LoginModel = await AuthApi.login(form)
    userStore.setToken(model.token)

    // 2.添加动态路由
    await initDynamicRouter()

    ElNotification.success({
      title: `登录成功`,
      message: '欢迎登录后台管理系统！'
    })
    const redirect: string = ($route.query?.redirect as string) || defaultConfig.HOME_URL
    $router.push({ path: redirect, replace: true })
  } catch (_) {
  } finally {
    loginLoading.value = false
  }
}
</script>
